import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2025-09-02
 * Time: 23:07
 */
//模拟实现阻塞队列
public class MyBlocKing {
    private Runnable[] list=null;    //阻塞队列
    private int head=0;              //队头
    private int last=0;              //队尾
    private int size=0;              //队列中元素个数
    private int size_max=0;          //队列大小
    private String lock="lock";
    MyBlocKing(){
        list=new Runnable[5];
        size_max=5;
    }
    MyBlocKing(int n){
        list=new Runnable[n];
        size_max=n;
    }
    public void put(Runnable run)throws InterruptedException{   //往队列中放元素
        while(size==size_max){
            synchronized (lock){
                lock.wait();
            }
        }
        synchronized(lock){
            list[last]=run;
            last++;
            if(last==size_max){
                last=0;
            }
            size++;
            lock.notify();
        }
    }
    public Runnable take()throws InterruptedException{        //从队列中取元素
        while (size==0){
            synchronized(lock){
                lock.wait();
            }
        }
        //Thread.sleep(500);
        Runnable run=null;
        synchronized(lock){
            run=list[head];
            head++;
            if(head==size_max){
                head=0;
            }
            size--;
            //Thread.sleep(500);
            lock.notify();
        }
        return run;
    }
}
